#include <bmCore/ViewerManager.h>
#include <osgGA/GUIEventHandler>
#include <stdlib.h>
#include <osgViewer/ViewerEventHandlers>
#include <osgWidget/ViewerEventHandlers>

namespace bmCore 
{

  class ViewChangeSizeHandler : public osgGA::GUIEventHandler
  {
    public:
      ViewChangeSizeHandler()
      {
      }
      virtual bool handle( const osgGA::GUIEventAdapter &ea, osgGA::GUIActionAdapter &aa )
      {
        switch ( ea.getEventType() )
        {
          case osgGA::GUIEventAdapter::RESIZE:
          {
            double width = ea.getWindowWidth();
            double height = ea.getWindowHeight();
            ViewerManager::Instance()->_windowSize.set( width, height );
          }
          break;
        default:
          break;
        }

        return false;
      }
  };



  ////////////////////////////////////////////////////////
  // ViewerManager
  ViewerManager::ViewerManager()
  {
    //_commandExec = new CommandExec;

  }

  ViewerManager::~ViewerManager()
  {
  }


  void ViewerManager::SetViewer( osgViewer::Viewer *v )
  {
    _viewer = v;
    _viewer->addEventHandler( new ViewChangeSizeHandler() );
    //_picker = new Picker();
    //_viewer->addEventHandler( _picker );

    _viewer->addEventHandler(new osgViewer::WindowSizeHandler());

    osg::DisplaySettings::instance()->setMinimumNumStencilBits(1);
    unsigned int clearMask = _viewer->getCamera()->getClearMask();
    _viewer->getCamera()->setClearMask(clearMask | GL_STENCIL_BUFFER_BIT);
    _viewer->getCamera()->setClearStencil(0);

  }

  osgViewer::Viewer *ViewerManager::GetViewer()
  {
    return _viewer.get();
  }
  osgViewer::Viewer *ViewerManager::GetViewer()const
  {
    return _viewer.get();
  }
/*
  CommandExec *ViewerManager::GetCommandExec()
  {
    return _commandExec;
  }
*/
  void ViewerManager::PreFrame()
  {
   // _commandExec->Exec();
  }

  void ViewerManager::Frame()
  {
    _viewer->frame();
  }
  void ViewerManager::PostFrame()
  {
  }


  osg::Vec2 ViewerManager::GetWindowSize()
  {
    return _windowSize;
  }

  void ViewerManager::SetWindowSize(const osg::Vec2 &s)
  {
     _windowSize = s;
  }

/*
  Picker *ViewerManager::GetPicker()
  {
    return _picker;
  }

  */
}
